const Service = require('egg').Service
const Sequelize = require('sequelize')
class ApiArticleService extends Service {
	constructor(ctx) {
		super(ctx)
	}

	async index(params) {
		let { pageSize = 10, pageNum = 1 } = params
		pageSize = Number(pageSize)
		const offset = (pageNum - 1) * pageSize
		const data = await this.ctx.model.Article.findAndCountAll({
			include: [
				{
					model: this.ctx.model.User,
					attributes: ['username'],
				},
				{
					model: this.ctx.model.Tag,
					attributes: ['tagName'],
				},
			],
			where: {
				status: 2,
			},
			limit: pageSize,
			offset,
			distinct: true,
		})
		return data
	}

	async homePage() {
		const data = await this.ctx.model.Article.findAll({
			include: [
				{
					model: this.ctx.model.User,
					attributes: ['username'],
				},
				{
					model: this.ctx.model.Tag,
					attributes: ['tagName'],
				},
			],
			where: {
				status: 2,
				showHome: 1,
			},
			distinct: true,
		})
		return data
	}

	async search(query) {
		const keyword = query.keyword
		let data = null
		if (query.type === 'author') {
			console.log('author')
			// 搜索用户id
			const users = await this.ctx.model.User.findAll({
				attributes: ['id'],
				where: {
					username: {
						[Sequelize.Op.like]: `%${keyword}%`,
					},
				},
				raw: true,
			})
			const infos = await this.ctx.model.UserInfo.findAll({
				attributes: ['userId'],
				where: {
					name: {
						[Sequelize.Op.like]: `%${keyword}%`,
					},
				},
				raw: true,
			})
			let infosArr = infos.map(item => {
				return item.userId
			})
			let usersArr = users.map(item => {
				return item.id
			})
			const ids = Array.from(new Set([...usersArr, ...infosArr]))
			data = await this.ctx.model.Article.findAll({
				where: {
					authorId: ids,
				},
			})
		} else if (query.type === 'title') {
			data = await this.ctx.model.Article.findAll({
				where: {
					title: {
						[Sequelize.Op.like]: `%${keyword}%`,
					},
				},
			})
		}
		return data
	}

	async show(id) {
		const body = await this.ctx.model.Article.findOne({
			include: [
				{
					model: this.ctx.model.User,
					attributes: ['username'],
				},
			],
			distinct: true,
            raw: true,
			where: { id },
		})
		const lastPage = await this.ctx.model.Article.findOne({
			attributes: ['id', 'title'],
			where: {
				id: {
					[Sequelize.Op.lt]: id,
				},
			},
			raw: true,
		})
		const nextPage = await this.ctx.model.Article.findOne({
            attributes: ['id', 'title'],
			where: {
				id: {
					[Sequelize.Op.gt]: id,
				},
			},
			raw: true,
		})
		if (body == null) {
			return {
				body,
				status: '不存在该数据',
			}
		} else {
			body.lastPage = lastPage
			body.nextPage = nextPage
            console.log(body)
			return {
				body,
				status: 'success',
			}
		}
	}
}

module.exports = ApiArticleService
